package com.zlx.sharelive.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.lzj.pass.dialog.PayPassDialog;
import com.lzj.pass.dialog.PayPassView;
import com.zlx.module_base.base_api.res_data.AuctionFriendBean;
import com.zlx.module_base.base_api.res_data.BaseBean;
import com.zlx.module_base.base_api.res_data.FriendBody;
import com.zlx.module_base.base_api.res_data.FriendListBean;
import com.zlx.module_base.base_api.res_data.PurchaseVideoBean;
import com.zlx.module_base.base_api.res_data.QueryByBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_fg.BaseFg;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.activity.AuctionAc;
import com.zlx.sharelive.activity.MyCompanionAc;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.bean.PartnerTimeBean;
import com.zlx.sharelive.utils.DecimalInputTextWatcher;
import com.zlx.sharelive.utils.StringUt;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 拍卖伴侣
 */
public class AuctionPartnerFg extends BaseFg {

    @BindView(R.id.tv_companion)
    TextView tv_companion;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.et_money)
    EditText et_money;

    private String over = "";
    private String day = "";
    private FriendListBean.InfoDTO.RecordsDTO mData;
    private List<PartnerTimeBean> mTimeList = new ArrayList<>();
    private CommonRecyclerViewAdapter<PartnerTimeBean> mTimeAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fg_auction_partner;
    }

    @Override
    protected void initViews() {
        super.initViews();

        initTimeData();
        moneyLimit();
        queryById();
    }

    /**
     * 查询余额
     */
    private void queryById() {
        ApiUtil.getLoginApi().queryById(SPUtil.getToken(getContext()),(String) SPUtil.get(getContext(), Constants.SP_ID, ""))
                .observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<QueryByBean>>() {
                    @Override
                    public void onSuccess(ApiResponse<QueryByBean> data) {
                        if (null != data) {
                            if (null != data.getData()) {
                                if (null != data.getData().getInfo()) {
                                    if (data.getData().getInfo().size() > 0) {
                                        if (null != data.getData().getInfo().get(0).getResult()) {
                                            if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getMoney())) {
                                                over = data.getData().getInfo().get(0).getResult().getMoney();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                }));
    }

    /**
     * 金钱限制
     */
    private void moneyLimit() {
        et_money.addTextChangedListener(new DecimalInputTextWatcher(et_money, 10, 2));
    }

    private void initTimeData() {
        mTimeList.clear();
        PartnerTimeBean partnerTimeBean1 = new PartnerTimeBean();
        partnerTimeBean1.setTime("1");
        partnerTimeBean1.setCheck(false);
        PartnerTimeBean partnerTimeBean2 = new PartnerTimeBean();
        partnerTimeBean2.setTime("3");
        partnerTimeBean2.setCheck(false);
        mTimeList.add(partnerTimeBean1);
        mTimeList.add(partnerTimeBean2);
    }

    @OnClick({R.id.iv_back, R.id.ll_please_choose, R.id.please_choose, R.id.bt_comm})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                ((AuctionAc) getActivity()).onFinish();
                break;
            case R.id.ll_please_choose:
                startActivityForResult(new Intent(getContext(), MyCompanionAc.class)
                        , 20);
                break;
            case R.id.please_choose:
                dialogTime();
                break;
            case R.id.bt_comm:
                if (StringUt.isEmpty(tv_companion.getText().toString().trim())) {
                    Toast.makeText(getContext(), "请选择伴侣", Toast.LENGTH_SHORT).show();
                    return;
                } else if (StringUt.isEmpty(day)) {
                    Toast.makeText(getContext(), "请选择时间", Toast.LENGTH_SHORT).show();
                    return;
                } else if (StringUt.isEmpty(et_money.getText().toString().trim())) {
                    Toast.makeText(getContext(), "请输入起拍价", Toast.LENGTH_SHORT).show();
                    return;
                } else if (
                        Double.valueOf(et_money.getText().toString().trim()) < 20000) {
                    Toast.makeText(getContext(), "请输入有效金额", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (!StringUt.isEmpty(et_money.getText().toString().trim())) {
                        if (Double.valueOf(et_money.getText().toString().trim()) < 20000 ||
                                Double.valueOf(et_money.getText().toString().trim()) == 20000) {
                            dialog(mData.getId(), "20000");
                        } else {
                            String money = String.valueOf(Double.valueOf(et_money.getText().toString().trim()) * 0.2);
                            dialog(mData.getId(), money);
                        }
                    }
                }
                break;
        }
    }

    /**
     * 缴纳金
     */
    private void dialog(String id, String money) {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getContext(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getContext(), R.layout.dialog_pay, null);
        dialog.setContentView(view);

        TextView tv_video_count = view.findViewById(R.id.tv_video_count);
        tv_video_count.setText(money);

        TextView tv_comm = view.findViewById(R.id.tv_comm);

        tv_comm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogPay(id, money, dialog);
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 购买
     */
    private void dialogPay(String id, String money, Dialog mDialog) {
        mDialog.dismiss();
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getContext(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getContext(), R.layout.dialog_play_video, null);
        dialog.setContentView(view);

        TextView tv_money = view.findViewById(R.id.tv_money);
        tv_money.setText("￥" + money);

        TextView tv_over = view.findViewById(R.id.tv_over);
        tv_over.setText("￥" + over);

        TextView bt_play = view.findViewById(R.id.bt_play);

        bt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUt.isEmpty(money) && !StringUt.isEmpty(over)) {
                    if (Double.valueOf(over) > Double.valueOf(money)) {
                        //钱够支付
                        dialogPass(id, money);
                        dialog.dismiss();
                    }
                }
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 支付密码
     */
    private void dialogPass(String id, String money) {
        PurchaseVideoBean purchaseVideoBean = new PurchaseVideoBean();
        purchaseVideoBean.setId(id);
        purchaseVideoBean.setMoney(money);

        final PayPassDialog dialog = new PayPassDialog(getContext());
        dialog.getPayViewPass()
                .setRandomNumber(true)
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String passContent) {
                        //6位输入完成回调
                        Log.d("ret", "joker  输入的密码===" + passContent);
                        goToPay(id, money, passContent, dialog);
                    }

                    @Override
                    public void onPayClose() {
                        dialog.dismiss();
                        //关闭弹框
                    }

                    @Override
                    public void onPayForget() {
                        dialog.dismiss();
                        //点击忘记密码回调
                    }
                });

    }

    /**
     * 缴纳金
     */
    private void goToPay(String id, String money, String pass, PayPassDialog dialog) {
        ApiUtil.getFriendApi().goToPay(SPUtil.getToken(getContext()),
                "1",
                money,
                id,
                pass
        ).observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
            @Override
            public void onSuccess(ApiResponse<BaseBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            auctionFriend(money);
                            dialog.dismiss();
                        } else {
                            Toast.makeText(getContext(), data.getData().getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        }));
    }

    /**
     * 拍卖伴侣
     */
    private void auctionFriend(String money) {
        FriendBody friendBody = new FriendBody();
        friendBody.setFriendId(mData.getId());
        friendBody.setDay(day);
        friendBody.setMoney(et_money.getText().toString().trim());
        ApiUtil.getFriendApi().auctionFriend(SPUtil.getToken(getContext()),
                friendBody
        ).observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<AuctionFriendBean>>() {
            @Override
            public void onSuccess(ApiResponse<AuctionFriendBean> data) {

            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));

//        ApiUtil.getFriendApi().auctionFriend(SPUtil.getToken(getContext()),
//                mData.getId(),
//                day,
//                money
//        ).observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<AuctionFriendBean>>() {
//            @Override
//            public void onSuccess(ApiResponse<AuctionFriendBean> data) {
//
//            }
//
//            @Override
//            public void onFinish() {
//                super.onFinish();
//
//            }
//        }));
    }

    private void dialogTime() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getContext(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getContext(), R.layout.dialog_partner_time, null);
        dialog.setContentView(view);

        RecyclerView dialog_recycler = view.findViewById(R.id.dialog_recycler);

        dialog_recycler.setLayoutManager(new LinearLayoutManager(getContext()));

        mTimeAdapter = new CommonRecyclerViewAdapter<PartnerTimeBean>(getContext(), mTimeList) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, PartnerTimeBean entity, int position) {
                TextView tv_text = holder.getView(R.id.tv_text);
                holder.setText(R.id.tv_text, entity.getTime() + "天");
                if (entity.isCheck() == true) {
                    tv_text.setTextColor(getResources().getColor(R.color.black));
                } else {
                    tv_text.setTextColor(getResources().getColor(R.color.martini));
                }
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_partner_time;
            }
        };

        dialog_recycler.setAdapter(mTimeAdapter);

        ImageView iv_close = view.findViewById(R.id.iv_close);

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        TextView tv_complete = view.findViewById(R.id.tv_complete);

        tv_complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (int i = 0; i < mTimeList.size(); i++) {
                    if (mTimeList.get(i).isCheck() == true) {
                        tv_time.setText(mTimeList.get(i).getTime());
                        day = mTimeList.get(i).getTime();
                    }
                }
                dialog.dismiss();
            }
        });

        mTimeAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                for (int i = 0; i < mTimeList.size(); i++) {
                    if (position == i) {
                        mTimeList.get(position).setCheck(true);
                    } else {
                        mTimeList.get(i).setCheck(false);
                    }
                }
                mTimeAdapter.notifyDataSetChanged();
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == data) {
            return;
        }
        if (resultCode == 30) {
            mData = (FriendListBean.InfoDTO.RecordsDTO) data.getSerializableExtra("data");
            tv_companion.setText(mData.getNickName());
        }
    }
}
